package com.love.poetry.application;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.common.collect.Lists;

import com.love.poetry.domain.Category;
import com.love.poetry.infrastructure.persist.CategoryRepository;

public class IniDataFilter extends HttpServlet implements Filter {

	private static final long serialVersionUID = 1L;
	protected FilterConfig filterConfig;
	private WebApplicationContext context = null;
	private List<Category> categories = Lists.newArrayList();
	
	@Autowired
	private CategoryRepository categoryRepository;
	
	@Override
	public void destroy() {
		this.filterConfig = null;
	}

	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if(context == null) {
			context = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext());
			categories = categoryRepository.queryTop();
		}
		
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		ServletContext context = httpServletRequest.getSession().getServletContext();
		context.setAttribute("categories", categories);
		
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

}